/* eslint-disable no-undef */
const puppeteer = require('puppeteer');
const Service = require('egg').Service;
const UserAgents = require('user-agents');
const uaPc = new UserAgents({ deviceCategory: 'desktop' });
const requestIntercept = (interceptedRequest) => {
  if (
    interceptedRequest.url().includes('.png') ||
    interceptedRequest.url().includes('.jpg') ||
    interceptedRequest.url().includes('.jpeg')
  ) {
    interceptedRequest.abort();
  } else interceptedRequest.continue();
};
class SubmitService extends Service {
  async send() {
    // @todo
  }
  async getQuery(url, proxyUrl) {
    const args = ['--no-sandbox', '--disable-setuid-sandbox'];
    if (proxyUrl) {
      args.unshift('--proxy-server=' + proxyUrl + '');
    }
    const browser = await puppeteer.launch({
      args,
    });
    const page = await browser.newPage();
    await page.setRequestInterception(true);
    page.on('request', requestIntercept);
    await page.setUserAgent(uaPc.random().toString());
    await page.goto(url, {
      waitUntil: ['networkidle2'],
    });
    const [query_string, sendUrl, cookie] = await page.evaluate(
      async function () {
        Object.defineProperty(navigator, 'webdriver', { get: () => false });
        // 获取地址
        const res = {
          submittype: 1,
          starttime: encodeURIComponent($('#starttime').val()),
        };
        res.cst = new Date().valueOf();
        res.ktimes = 1;
        if (window.rndnum) {
          res.rn = encodeURIComponent(window.rndnum);
        }
        if (window.jqnonce) {
          res.jqnonce = encodeURIComponent(window.jqnonce);
          if (window.dataenc) {
            res.jqsign = encodeURIComponent(window.dataenc(window.jqnonce));
          }
        }
        if (window.jqParam) {
          res.jqpram = encodeURIComponent(window.jqParam);
        }
        res.t = new Date().getTime();
        if (window.nw) {
          res.nw = encodeURIComponent(window.nw);
        }
        if (window.hlv) {
          res.hlv = encodeURIComponent(window.hlv);
        }
        const sendUrl = $('#form1').attr('action');
        const cookie = document.cookie;
        return [res, sendUrl, cookie];
      }
    );
    page.removeListener('request', requestIntercept);
    await page.close();
    await browser.close();
    return {
      sendUrl,
      query_string,
      cookie,
    };
  }
}

module.exports = SubmitService;
